const { ipcRenderer } = require('electron');
const EmailService = require('./email-service');

let store;
import('electron-store').then(Store => {
    store = new Store.default();
    initApp();
}).catch(err => {
    console.error('Failed to load electron-store:', err);
});

// 这里应该从某个安全的地方获取用户凭证
// const emailService = new EmailService('example@mail.com', 'BLQeEqEm3KV8RK9d');

function initApp() {
    const composeBtn = document.getElementById('compose-btn');
    const emailList = document.getElementById('email-list');
    const emailPreview = document.getElementById('email-preview');
    const folderListItems = document.querySelectorAll('#folder-list li');

    let allEmails = [];
    let emailService;


    function initEmailService() {
        const email = store.get('email');
        const password = store.get('password');
        if (email && password) {
            emailService = new EmailService(email, password);
            fetchEmails();
        } else {
            alert('请先设置邮箱账户');
            ipcRenderer.send('open-settings-window');
        }
    }

    initEmailService();

    // 添加设置按钮的事件监听器
    document.getElementById('settings-btn').addEventListener('click', () => {
        ipcRenderer.send('open-settings-window');
    });

    // 监听设置更新事件
    ipcRenderer.on('reload-email-service', () => {
        initEmailService();
    });    

    composeBtn.addEventListener('click', () => {
        console.log('撰写邮件按钮被点击');
        ipcRenderer.send('open-compose-window');
    });

    // 为每个文件夹列表项添加点击事件监听器
    folderListItems.forEach(item => {
        item.addEventListener('click', () => {
            const folderName = item.getAttribute('data-folder');
            fetchEmails(folderName);
        });
    });

    function fetchEmails(folderName = 'INBOX') {
        emailList.innerHTML = '<p>正在加载邮件...</p>';
        emailService.fetchEmails(folderName)
            .then(emails => {
                allEmails = emails;
                renderEmailList(emails);
            })
            .catch(error => {
                console.error('获取邮件失败:', error);
                emailList.innerHTML = '<p>获取邮件失败，请重试。</p>';
            });
    }

    function renderEmailList(emails) {
        emailList.innerHTML = '';
        if (emails.length === 0) {
            emailList.innerHTML = '<p>没有邮件。</p>';
            return;
        }
        emails.forEach(email => {
            const emailItem = document.createElement('div');
            emailItem.className = 'email-item';
            emailItem.innerHTML = `
                <div class="email-sender">${email.from}</div>
                <div class="email-subject">${email.subject}</div>
                <div class="email-date">${formatDate(email.date)}</div>
            `;
            emailItem.addEventListener('click', () => showEmailPreview(email));
            emailList.appendChild(emailItem);
        });
    }

    function formatDate(date) {
        const now = new Date();
        const emailDate = new Date(date);
        if (emailDate.toDateString() === now.toDateString()) {
            return emailDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        } else {
            return emailDate.toLocaleDateString();
        }
    }

    function showEmailPreview(email) {
        emailPreview.innerHTML = `
            <h2>${email.subject}</h2>
            <p>From: ${email.from}</p>
            <p>Date: ${formatDate(email.date)}</p>
            <div class="email-content">${email.text}</div>
            <button id="reply-btn">回复</button>
            <button id="mark-important-btn">标记为重要</button>
            <button id="move-to-spam-btn">移至垃圾邮件</button>
        `;
        
        document.getElementById('reply-btn').addEventListener('click', () => {
            openComposeWindow(email);
        });

        document.getElementById('mark-important-btn').addEventListener('click', () => {
            emailService.markEmail(email.id, '\\Flagged')
                .then(() => alert('邮件已标记为重要'))
                .catch(error => console.error('标记邮件失败:', error));
        });

        document.getElementById('move-to-spam-btn').addEventListener('click', () => {
            emailService.moveEmail(email.id, 'Spam')
                .then(() => {
                    alert('邮件已移至垃圾邮件文件夹');
                    fetchEmails(); // 刷新邮件列表
                })
                .catch(error => console.error('移动邮件失败:', error));
        });
    }

    function showEmailPreview(email) {
        emailPreview.innerHTML = `
            <h2>${email.subject}</h2>
            <p>From: ${email.from}</p>
            <p>Date: ${formatDate(email.date)}</p>
            <div class="email-content">${email.text}</div>
            <button id="reply-btn">回复</button>
        `;
        
        document.getElementById('reply-btn').addEventListener('click', () => {
            openComposeWindow(email);
        });
    }

    document.getElementById('search-input').addEventListener('input', (e) => {
        const searchTerm = e.target.value.toLowerCase();
        const filteredEmails = allEmails.filter(email => 
            (email.subject && email.subject.toLowerCase().includes(searchTerm)) ||
            (email.from && email.from.toLowerCase().includes(searchTerm)) ||
            (email.text && email.text.toLowerCase().includes(searchTerm))
        );
        renderEmailList(filteredEmails);
    });

    function openComposeWindow(replyToEmail = null) {
        ipcRenderer.send('open-compose-window', replyToEmail);
    }

    // 初始化时获取邮件列表
    // fetchEmails();
}

